package com.example.szh.mvp.view.news;

import android.Manifest;
import android.os.Build;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.szh.R;
import com.example.szh.adapter.CommentAdapter;
import com.example.szh.db.DBManager;
import com.example.szh.entity.BaseEntity;
import com.example.szh.entity.CommentEntity;
import com.example.szh.entity.UserEntity;
import com.example.szh.http.HttpCode;
import com.example.szh.mvp.contract.LREContract;
import com.example.szh.mvp.di.DaggerLREConponent;
import com.example.szh.mvp.di.LREMoudes;
import com.example.szh.mvp.presenter.LREPresenter;
import com.example.szh.nextwork.view.BaseActivity;
import com.example.szh.utils.LogUtils;
import com.example.szh.utils.ToastUtils;
import com.example.szh.widget.x5.X5WebView;
import com.google.android.material.appbar.AppBarLayout;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsValuesActivity extends BaseActivity<LREPresenter> implements LREContract.ILREView ,
        View.OnClickListener, FaceFragment.OnEmojiClickListener , AppBarLayout.OnOffsetChangedListener, OnRefreshLoadMoreListener {


    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    private RelativeLayout webValuesTop;
    private ImageView headBackImg;
    private RelativeLayout webValuesBottomRelative;
    private ImageView liveShareImg;
    private ImageView liveCollectionImg;
    private RelativeLayout liveMsgRelative;
    private View webValuesLine;
    private X5WebView webValuesX5;
    private RecyclerView commonRv;
    private RelativeLayout liveBottomView;
    private EditText liveMsgEdt;
    private ImageView liveVoiceImg;
    private ImageView liveEmojiImg;
    private LinearLayout liveEmojiLinear;
    private RecyclerView liveEmojiRv;
    private ImageView livePointImg1;
    private ImageView livePointImg2;
    private long news_id=0;
    private String news_url;
    private CommentAdapter commentAdapter;
    private View headView;
    private RelativeLayout webValuesRoot;
    private RelativeLayout liveEdtBnt;
    private ImageView liveFace;
    private TextView liveSendTv;
    private List<UserEntity> list;
    private AppBarLayout webValuesAppbar;
    private TextView liveMsgNumTv;
    private boolean appFlag=true;
    private int oldverticalOffset;
    private SmartRefreshLayout wenValuesSmart;
    private String address="";
    private int num=1;

    @Override
    public View addStatusView() {
        return f(R.id.web_values_root);
    }

    @Override
    public void refreshAll(BaseEntity entity) {
        if (entity instanceof CommentEntity){
            CommentEntity commentEntity = (CommentEntity) entity;
            commentAdapter.setNewData(commentEntity.getValues());
        }else if (entity.message.equals("失败")){
            com.blankj.utilcode.util.LogUtils.json(entity);
            liveCollectionImg.setImageResource(R.drawable.res_7icon_128);
            num=1;
        }else if (entity.message.equals("成功")){
            com.blankj.utilcode.util.LogUtils.json(entity);
            liveCollectionImg.setImageResource(R.drawable.kind_on);
            num=0;
        }else if (entity.message.equals("收藏成功")){
            ToastUtils.showMsg("收藏成功");
        }else if (entity.message.equals("取消藏成功")){
            ToastUtils.showMsg("取消藏成功");
        } else {
            if (entity.message.equals("发表成功")){
                //当前评论发布成功
                liveMsgEdt.setText("");
                initData();
            }
        }
    }

    @Override
    public void refreshRecyckerView(BaseEntity entity) {
        CommentEntity commentEntity = (CommentEntity) entity;
        if (commentEntity==null){
            ToastUtils.showMsg("没有评论");
            return;
        }
        commentAdapter.setNewData(commentEntity.getValues());
    }

    @Override
    public void loadMoreRecyclerView(BaseEntity entity) {
        CommentEntity commentEntity = (CommentEntity) entity;
        if (commentEntity==null){
            ToastUtils.showMsg("最后一页");
            return;
        }
        commentAdapter.addData(commentEntity.getValues());
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_news_values;
    }

    @Override
    public void initView() {
        headView= LayoutInflater.from(this).inflate(R.layout.view_web_values, null);
        news_url = getIntent().getExtras().getString("news_url");
        news_id = getIntent().getExtras().getLong("news_id",0);
        webValuesTop = (RelativeLayout) findViewById(R.id.web_values_top);
        headBackImg = (ImageView) findViewById(R.id.head_back_img);
        headBackImg.setOnClickListener(this::onClick);
        webValuesBottomRelative = (RelativeLayout) findViewById(R.id.web_values_bottom_relative);
        liveShareImg = (ImageView) findViewById(R.id.live_share_img);
        liveCollectionImg = (ImageView) findViewById(R.id.live_collection_img);
        liveCollectionImg.setOnClickListener(this::onClick);
        liveMsgRelative = (RelativeLayout) findViewById(R.id.live_msg_relative);
        webValuesLine = (View) findViewById(R.id.web_values_line);
        webValuesX5 = (X5WebView) findViewById(R.id.web_values_x5);
        commonRv = f(R.id.common_rv);
        liveBottomView = (RelativeLayout) findViewById(R.id.live_bottom_view);
        liveMsgEdt = (EditText) findViewById(R.id.live_msg_edt);
        liveVoiceImg = (ImageView) findViewById(R.id.live_voice_img);
        liveEmojiImg = (ImageView) findViewById(R.id.live_emoji_img);
        liveEmojiLinear = (LinearLayout) findViewById(R.id.live_emoji_linear);
//        liveEmojiRv = (RecyclerView) findViewById(R.id.live_emoji_rv);
//        livePointImg1 = (ImageView) findViewById(R.id.live_point_img1);
//        livePointImg2 = (ImageView) findViewById(R.id.live_point_img2);
        webValuesX5.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (!s.contentEquals("http://118.195.161.134:8066/"))
                    return true;
                return false;
            }
        });
        getSupportFragmentManager().beginTransaction().add(R.id.live_emoji_linear,
                FaceFragment.Instance()).commit();
        webValuesX5.loadUrl(news_url);
        LinearLayoutManager manager=new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        commonRv.setLayoutManager(manager);
        commentAdapter=new CommentAdapter();
        commentAdapter.addHeaderView(headView);
        commonRv.setAdapter(commentAdapter);
//        commentAdapter.setEmptyView();
//        commentAdapter.setEmptyView(R.layout.view_empty);
        webValuesRoot = (RelativeLayout) findViewById(R.id.web_values_root);
        liveEdtBnt = (RelativeLayout) findViewById(R.id.live_edt_bnt);
        liveFace = (ImageView) findViewById(R.id.live_face);
        liveSendTv = (TextView) findViewById(R.id.live_send_tv);
        liveEdtBnt.setOnClickListener(this::onClick);
        liveFace.setOnClickListener(this::onClick);
        liveEmojiImg.setOnClickListener(this::onClick);
        liveSendTv.setOnClickListener(this::onClick);
        webValuesAppbar = (AppBarLayout) findViewById(R.id.web_values_appbar);
        liveMsgNumTv = (TextView) findViewById(R.id.live_msg_num_tv);
        liveMsgRelative.setOnClickListener(this::onClick);
        webValuesAppbar.addOnOffsetChangedListener(this);
        wenValuesSmart = (SmartRefreshLayout) findViewById(R.id.wen_values_smart);
        wenValuesSmart.setEnableRefresh(true);
        wenValuesSmart.setEnableLoadMore(true);
        wenValuesSmart.setRefreshHeader(new ClassicsHeader(this));
        wenValuesSmart.setRefreshFooter(new ClassicsFooter(this));
        wenValuesSmart.setOnRefreshLoadMoreListener(this);

    }

    @Override
    public void inject() {
        DaggerLREConponent.builder().lREMoudes(new LREMoudes(this)).build().injectNewsValuesActivity(this);
    }

    @Override
    public void initData() {
        Map<String,Object> collMap=new HashMap<>();
        collMap.put("code", HttpCode.ISCollectNewsCODE);
        collMap.put("news_id",news_id);
        collMap.put("user_id", 1);
        p.requestAll(collMap);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.LOADER_USAGE_STATS,
            }, 101);
        }
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();

        option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true

        option.setNeedNewVersionRgc(true);
//可选，设置是否需要最新版本的地址信息。默认需要，即参数为true

        mLocationClient.setLocOption(option);
        //注册监听函数
        Map<String,Object> map=new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestAll(map);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息
            address=city;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.live_edt_bnt:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.GONE);
                break;
            case R.id.live_face:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.VISIBLE);
                break;
            case R.id.live_emoji_img:
                if (liveEmojiLinear.getVisibility()==View.VISIBLE){
                    liveEmojiLinear.setVisibility(View.GONE);
                    liveEmojiImg.setImageResource(R.drawable.res_7icon_129);
                }else {
                    liveEmojiLinear.setVisibility(View.VISIBLE);
                    liveEmojiImg.setImageResource(R.drawable.res_7icon_131);
                }
                break;
            case R.id.live_send_tv:
                if (liveMsgEdt.getText()==null){
                    ToastUtils.showMsg("请出入评论内容");
                    return;
                }
                if (liveMsgEdt.getText().toString().isEmpty()){
                    ToastUtils.showMsg("请出入评论内容");
                    return;
                }
                try {
                    list = DBManager.getInstance().getDaoSession().queryBuilder(UserEntity.class).list();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mLocationClient.start();
                Map<String,Object> map=new HashMap<>();
                map.put("code", HttpCode.ADDCOMMENTCODE);
                LogUtils.e(address);
                map.put("comment_address",address);
                map.put("comment_time",System.currentTimeMillis()/1000);
                map.put("comment_value",liveMsgEdt.getText().toString());
                map.put("news_id",news_id);
                map.put("user_id",list.get(0).getUser_id());
                p.requestAll(map);
                break;
            case R.id.head_back_img:
                finish();
                break;
            case R.id.live_msg_relative:
                if (appFlag){
                    liveMsgNumTv.setText("正文");
                }else {
                    liveMsgNumTv.setText("937");
            }
                appFlag=!appFlag;
                webValuesAppbar.setExpanded(appFlag);
                break;
            case R.id.live_collection_img:
                Map<String,Object> collMap=new HashMap<>();
                collMap.put("code", HttpCode.ISCollectNewsCODE);
                collMap.put("news_id",news_id);
                collMap.put("user_id", 1);
                p.requestAll(collMap);
                if (num==1){
                    Map<String,Object> addcollMap=new HashMap<>();
                    addcollMap.put("code", HttpCode.ADDCollectNewsCODE);
                    addcollMap.put("news_id",news_id);
                    addcollMap.put("user_id", 1);
                    p.requestAll(addcollMap);
                    liveCollectionImg.setImageResource(R.drawable.kind_on);
                }else {
                    Map<String,Object> delcollMap=new HashMap<>();
                    delcollMap.put("code", HttpCode.DELCollectNewsCODE);
                    delcollMap.put("news_id",news_id);
                    delcollMap.put("user_id", 1);
                    p.requestAll(delcollMap);
                    liveCollectionImg.setImageResource(R.drawable.res_7icon_128);
                }
                break;

        }
    }

    @Override
    public void onEmojiDelete() {
        String text = liveMsgEdt.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                try {
                    EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            liveMsgEdt.getText().delete(index, text.length());
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        try {
            EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = liveMsgEdt.getSelectionStart();
            Editable editable = liveMsgEdt.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (liveBottomView.getVisibility()==View.VISIBLE){
                liveBottomView.setVisibility(View.GONE);
                return true;
            }else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (oldverticalOffset==verticalOffset){
            return;
        }
        if (verticalOffset==0){
            //当前显示正文
            appFlag=true;
            liveMsgNumTv.setText("937");
        }else {
            appFlag=false;
            liveMsgNumTv.setText("正文");
        }
        oldverticalOffset=verticalOffset;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore();
        Map<String,Object> map=new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestLoad(map);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh();
        Map<String,Object> map=new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestRefresh(map);
    }
}